# encoding:utf-8
import datetime
import time


def get_before_time(timestamp, hours, format='%Y-%m-%d %H:%M:%S'):
    """
    以给定时间戳为基准，后退 hours 个小时得到对应的时间戳
    :param timestamp:
    :param hours:
    :param format:
    :return:
    """
    now_time = datetime.datetime.strptime(timestamp, '%Y-%m-%d %H:%M:%S')
    for i in range(hours):
        now_time -= datetime.timedelta(hours=1)
    next_timestamp = now_time.strftime('%Y-%m-%d %H:%M:%S')
    return next_timestamp


def get_future_time(timestamp, hours, format='%Y-%m-%d %H:%M:%S'):
    """
    以给定时间戳为基准，前进 hours 个小时得到对应的时间戳
    """
    now_time = datetime.datetime.strptime(timestamp, '%Y-%m-%d %H:%M:%S')
    for i in range(hours):
        now_time += datetime.timedelta(hours=1)
    next_timestamp = now_time.strftime('%Y-%m-%d %H:%M:%S')
    return next_timestamp


def get_after_timestamp_ms(current_timestamp_ms, seconds):
    # 将当前时间戳转换为秒级时间戳
    current_timestamp_s = current_timestamp_ms // 1000
    # 计算6小时后的时间戳（以秒为单位）
    six_hours_later_timestamp_s = current_timestamp_s + seconds
    # 将6小时后的时间戳转换为毫秒级时间戳
    six_hours_later_timestamp_ms = six_hours_later_timestamp_s * 1000
    return six_hours_later_timestamp_ms


def get_time_str_before_now_s(seconds):
    """获取给定秒数seconds之前于当前时间的字符串"""
    datetime_obj = datetime.datetime.now() - datetime.timedelta(seconds=seconds)
    return datetime_obj.strftime('%Y-%m-%d %H:%M:%S')


def get_utc_time_str_before_now_s(seconds):
    """获取给定秒数seconds之前于当前时间的UTC时间字符串"""
    datetime_obj = datetime.datetime.utcnow() - datetime.timedelta(seconds=seconds)
    return datetime_obj.strftime('%Y-%m-%d %H:%M:%S')


def get_timestamp_before_now(seconds):
    """获取给定秒数seconds之前于当前时间的时间戳"""
    datetime_obj = datetime.datetime.now() - datetime.timedelta(seconds=seconds)
    return get_time_stamp13(datetime_obj)


def get_time_stamp10(datetime_obj):
    """生成10位时间戳   eg:1557842287"""
    # 10位，时间点相当于从1.1开始的当年时间编号
    return str(int(time.mktime(datetime_obj.timetuple())))


def get_time_stamp13(datetime_obj):
    """生成13位时间戳   eg:1557842287123"""
    time_stamp_10 = get_time_stamp10(datetime_obj)
    # 3位，微秒
    time_microsecond = str("%06d" % datetime_obj.microsecond)[0:3]
    time_stamp = time_stamp_10 + time_microsecond
    return int(time_stamp)


def get_time_stamp10_now():
    """生成当前时间的10位时间戳   eg:1557842287"""
    return get_time_stamp10(datetime.datetime.now())


def get_time_stamp13_now():
    """生成当前时间的13位时间戳   eg:1557842287123"""
    return get_time_stamp13(datetime.datetime.now())


def timestamp_to_formated_str(timestamp, format_str="%Y-%m-%d %H:%M:%S"):
    """
    将timestamp转换为指定格式的字符串。
    :param timestamp: 时间戳（秒为单位的浮点数）。
    :param format_str: 转换后的日期时间格式字符串，默认为"YYYY-MM-DD HH:MM:SS"。
    :return 指定格式的日期时间字符串。
    """
    # 如果timestamp是以毫秒为单位，需要除以1000转换为秒
    if timestamp > 1e10:  # 简单判断timestamp是否可能是毫秒级别
        timestamp /= 1000
    dt_object = datetime.datetime.fromtimestamp(timestamp)
    return dt_object.strftime(format_str)


if __name__ == '__main__':
    print(get_timestamp_before_now(180))
    print(get_time_str_before_now_s(180))
    millis_example = 1714287884218
    formatted_millis = timestamp_to_formated_str(millis_example)
    print(formatted_millis)  # 输出同样格式的时间字符串
    # timestamp = '2018-12-19 11:00:00'
    # print(get_before_time("1695282458", 2, format='%Y-%m-%d %H:%M:%S'))
    # print(get_future_time(timestamp, 2, format='%Y-%m-%d %H:%M:%S'))
    # print(get_after_timestamp_ms(int(time.time() * 1000), 6*60*60))
    interval_start = 60 * 3
    interval_end = 60 * 9
    import random

    # 1.判断当前时间是否在当天可发送的时间范围内，
    # 如果小于可发送时间，则开始时间为当天的发送时间
    # 如果大于可发送时间，则从明天开始发送
    cas_fmt_time = "2023-11-24 20:00:00"
    cae_fmt_time = "2023-11-24 23:00:00"
    dt_now = datetime.datetime.now()
    dt_cas = datetime.datetime.strptime(cas_fmt_time, '%Y-%m-%d %H:%M:%S')
    dt_cae = datetime.datetime.strptime(cae_fmt_time, '%Y-%m-%d %H:%M:%S')
    print('当前时间', dt_now)
    print('最早开始时间', dt_cas)
    print('最晚开始时间', dt_cae)
    start_time = dt_now
    if dt_now < dt_cas:  # 如果小于可发送时间，则开始时间为当天的发送时间
        start_time = dt_cas
        print('今天预计的时间开发', start_time)
    elif dt_cas < dt_now < dt_cae:
        print('此时开始发送', start_time)
        pass
    elif dt_now > dt_cae:
        start_time = dt_cas + datetime.timedelta(days=1)  # 如果大于可发送时间，则从明天开始发送
        dt_cas = start_time
        dt_cae = dt_cae + datetime.timedelta(days=1)
        print('明天开始发送', start_time)
    else:
        print('其他时间')
        start_time = dt_now

    start_time = start_time + datetime.timedelta(seconds=3)  # 3秒后开始执行第一个任务
    for i in range(100):
        run_time = start_time.strftime("%Y-%m-%d %H:%M:%S.%f")  # 生成每组数据的间隔时间(秒)
        task_id = str(i) + '_' + str(run_time)  # 根据时间戳(ms)作为唯一表示
        # print('每组任务的运行时间：', run_time)
        # 根据 interval_start 和 interval_end生成一个随机时间
        random_int = random.randint(interval_start, interval_end)
        start_time = start_time + datetime.timedelta(seconds=random_int)
        if start_time > dt_cae:
            # 开始日期+1天
            dt_cas = dt_cas + datetime.timedelta(days=1) + datetime.timedelta(microseconds=random.randint(100000, 999999))
            dt_cae = dt_cae + datetime.timedelta(days=1)  # 结束日期+1天
            start_time = dt_cas  # 下次开始时间设置为明天第一时刻
